package ru.arriah.servicedesk.web.dispatcher;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.bean.MessageBean;
import ru.arriah.common.web.UIController;
import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.servicedesk.bean.EmployeeBean;
import ru.arriah.servicedesk.bean.IntWrapper;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.LoginException;


public class OperatorUI extends UIController {
   protected EmployeeManagerLocalHome employeeManagerHome;
   protected RequestManagerLocalHome requestManagerHome;
   
   public OperatorUI() {
      super();
   }

   
   /**
    * @deprecated
    * @param request
    * @return
    */
   protected String getUserIdFromCookie(HttpServletRequest request) {     
     Cookie[] cookies = request.getCookies();
          
     String value = null;
     for(Cookie cookie : cookies)  {
       if(cookie.getName().equals("userId")) {
         value = cookie.getValue();
       }
     }
     return value;
   }
   
   
   public void init(ServletConfig config) throws ServletException {
      super.init(config);
      try {
         employeeManagerHome =
            Utils.getEmployeeManagerHomeInterface();
         requestManagerHome = 
            Utils.getRequestManagerHomeInterface();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
   
   
   protected void prologue(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {          
      
      request.getSession().setAttribute("alias", "operatorui");
      Object userId = Utils.getUserId(request);      
      
      if (
         userId == null && !actionMapping.getActionName().equals("login")
      ) {          
         throw new LoginException("ErrorMessage.relogin");
      }

      String uri = request.getRequestURI();
      String query = request.getQueryString();

      if (query != null) {
         uri += "?" + query;
      }

      String uriEncoded = URLEncoder.encode(uri, "UTF-8");
      request.setAttribute("uri", uri);
      request.setAttribute("uriEncoded", uriEncoded);
      
      /* messages list */     
      request.setAttribute(
         "messagesList", 
         new ArrayList<MessageBean>()
      );
   }

   private void displayUserName(HttpServletRequest request) {
      try {
         int userId = Utils.getUserId(request);
         
         EmployeeManagerLocalObject employeeManager = 
            employeeManagerHome.create();
         
         EmployeeBean employeeBean = 
            employeeManager.selectEmployee(userId);
                  
         request.setAttribute("userName", employeeBean.getFormName());
         
         employeeManager.remove();
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }     
   }
   
   
   private void displaySideBarList(HttpServletRequest request) {
      try {         
         RequestManagerLocalObject requestManager = 
            requestManagerHome.create();                         
         
//         if (request.getSession().getAttribute("sidebarpage") == null)
//            request.getSession().setAttribute(
//               "sidebarpage", 
//               Utils.idVal(request.getParameter("sidebarpage"))
//            ); 
         
         if (request.getParameter("sidebarpage") != null) {
            request.getSession().setAttribute(
               "sidebarpage", 
               Utils.idVal(request.getParameter("sidebarpage"))
            ); 
         }
         
         if ("true".equals(request.getParameter("_allRequests")))
            request.getSession().removeAttribute("searchRequestTemplate");         
         
         int page = (request.getSession().getAttribute("sidebarpage") == null) ? 0 : (Integer)request.getSession().getAttribute("sidebarpage");
         
         int itemsPerPage = 5;         
         
         IntWrapper records = new IntWrapper(0);         
         
         String order = request.getParameter("sidebarorder");
         String orderBy = request.getParameter("sidebarorderBy");
         
         order = (order == null) ? "N" : order;                
         orderBy = (orderBy == null) ? "DESC" : orderBy;                               
         
         Collection<RequestBean> requestsList = null;
         
         RequestBean searchRequestTemplate = 
            (RequestBean)request.getSession().getAttribute("searchRequestTemplate");
         
         if (searchRequestTemplate != null)
            requestsList = 
               requestManager.searchRequests(
                  searchRequestTemplate,
                  orderBy, 
                  order,
                  page,
                  itemsPerPage,
                  records
               );
         else
            requestsList = 
               requestManager.selectRequests(
                  orderBy, 
                  order,
                  page,
                  itemsPerPage,
                  records
               );              
                  
         request.setAttribute("requestsList", requestsList);
         Utils.pageNavigationToRequest(
             page,          
             records.getValue(), 
             "operatorui?_action=dumb&sidebarpage=",
             request,
             "sidebarpaging",
             "sidebarcurrentpage"
          );
         
         requestManager.remove();                                    
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }     
   }
   
   
   protected void epilogue(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
      try {         
         this.displaySideBarList(request);
         this.displayUserName(request);
      } catch (Exception e) {
         handleException(e, "epilogue");
      }
   }
}